package cn.hdu.liang.core.service.staticpage;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Map;

/**
 * 生成静态页 实现类
 */
@Service
public class StaticPageServiceImpl implements StaticPageService, ServletContextAware {

    private Configuration conf;

    private ServletContext servletContext;

    //获取路径
    public String getPath(String name) {
        return servletContext.getRealPath(name);
    }

    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.conf = freeMarkerConfigurer.getConfiguration();
    }

    //静态化方法
    @Override
    public void productIndex(Map<String, Object> data, Integer id) {

        //获取HTML路径
        String path = getPath("/html/product/" + id + ".html");
        File file = new File(path);
        File parentFile = file.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }

        try(Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8")) {
            //以UTF-8读取 磁盘到内存
            Template template = conf.getTemplate("productDetail.html");
            //处理模板
            template.process(data, out);
        } catch(IOException e) {
            e.printStackTrace();
        } catch(TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
